<template>
  <div class="property-company-list">
    <!-- 没有关联物业公司的提示 -->
    <NoPropertyCompany 
      v-if="!hasPropertyCompany" 
      title="暂未关联物业公司"
      description="当前用户暂未关联任何物业公司，无法查看和编辑物业公司信息。"
      icon="Warning"
      :show-contact-tip="true"
      :show-actions="true"
      :show-refresh-button="true"
      :show-contact-button="true"
      refresh-button-text="重新检查"
      contact-button-text="联系管理员"
      @refresh="handleRefresh"
      @contact="handleContactAdmin"
    />

    <!-- 有关联物业公司时显示列表 -->
    <div v-else>
      <!-- 搜索区域 -->
      <el-card class="search-card" shadow="never">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="80px">
          <el-form-item label="公司名称" prop="companyName">
            <el-input
              v-model="queryParams.companyName"
              placeholder="请输入公司名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="公司编码" prop="companyCode">
            <el-input
              v-model="queryParams.companyCode"
              placeholder="请输入公司编码"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input
              v-model="queryParams.contactPerson"
              placeholder="请输入联系人"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input
              v-model="queryParams.contactPhone"
              placeholder="请输入联系电话"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              style="width: 200px"
            >
              <el-option :label="STATUS.ENABLED" :value="1" />
              <el-option :label="STATUS.DISABLED" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="资质等级" prop="qualificationLevel">
            <el-select
              v-model="queryParams.qualificationLevel"
              placeholder="请选择资质等级"
              clearable
              style="width: 200px"
            >
              <el-option label="一级" value="一级" />
              <el-option label="二级" value="二级" />
              <el-option label="三级" value="三级" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetQuery">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 操作按钮区域 -->
      <el-card class="operation-card" shadow="never">
        <div class="operation-buttons">
          <el-button type="primary" @click="handleAdd" v-if="isSuperAdmin">
            <el-icon><Plus /></el-icon>
            新增
          </el-button>

          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </div>
      </el-card>

      <!-- 数据表格区域 -->
      <el-card class="table-card" shadow="never">
        <el-table
          v-loading="loading"
          :data="propertyCompanyList"
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="公司名称" prop="companyName" min-width="80" show-overflow-tooltip />
          <el-table-column label="公司编码" prop="companyCode" width="170" />
          <el-table-column label="联系人" prop="contactPerson" width="90" />
          <el-table-column label="联系电话" prop="contactPhone" width="120" />
          <el-table-column label="资质等级" prop="qualificationLevel" width="90" />
          <el-table-column label="状态" prop="status" width="70" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" prop="auditStatus" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="getAuditStatusType(row.auditStatus)">
                {{ getAuditStatusText(row.auditStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" width="160" align="center">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240" align="center" fixed="right">
            <template #default="{ row }">
              <div class="operation-buttons">
                <el-button type="primary" link size="small" @click="handleView(row)">
                  详情
                </el-button>
                <el-button type="warning" link size="small" @click="handleAddUser(row)" v-if="isSuperAdmin">
                  新增用户
                </el-button>
                <el-button type="primary" link size="small" @click="handleAudit(row)" v-if="row.auditStatus === 0 && isSuperAdmin">
                  审核
                </el-button>
                <el-button type="danger" link size="small" @click="handleDelete(row)" v-if="isSuperAdmin">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 20px; justify-content: flex-end"
        />
      </el-card>

      <!-- 新增对话框 -->
      <PropertyCompanyForm
        ref="formRef"
        :visible="formVisible"
        :form-data="formData"
        :is-edit="false"
        @success="handleFormSuccess"
        @cancel="handleFormCancel"
      />

      <!-- 审核对话框 -->
      <PropertyCompanyAudit
        ref="auditRef"
        :visible="auditVisible"
        :company-id="auditCompanyId"
        @success="handleAuditSuccess"
        @cancel="handleAuditCancel"
      />

    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * 物业公司列表页面
 * @author Wu.Liang
 * @date 2025-01-29
 */

import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { STATUS } from '@/constants/status'
import { Search, Refresh, Plus, Delete, Download, Warning } from '@element-plus/icons-vue'
import propertyCompanyApi from '@/api/property/propertyCompany'
import { propertyInfoApi } from '@/api/property/propertyInfo'
import { useUserStore } from '@/store/user'
import { usePermissionStore } from '@/store/permission'
import PropertyCompanyForm from './components/PropertyCompanyForm.vue'
import PropertyCompanyAudit from './components/PropertyCompanyAudit.vue'
import NoPropertyCompany from '@/components/NoPropertyCompany/index.vue' // 引入无物业公司提示组件
import { showSuccess, showError, showInfo, showWarning } from '@/utils/message'

// 用户store
const userStore = useUserStore()
const permissionStore = usePermissionStore()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const propertyCompanyList = ref<any[]>([])
const total = ref(0)
const selectedIds = ref<number[]>([])
const queryFormRef = ref()
const formRef = ref()
const auditRef = ref()

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  companyName: '',
  companyCode: '',
  contactPerson: '',
  contactPhone: '',
  status: undefined as any,
  auditStatus: undefined as any,
  qualificationLevel: ''
})

// 表单相关
const formVisible = ref(false)
const formData = ref<any>({})

// 审核相关
const auditVisible = ref(false)
const auditCompanyId = ref<number>(0)

// 物业公司关联状态
const hasPropertyCompany = ref(false)

// 计算属性
const hasSelection = computed(() => selectedIds.value.length > 0)

// 权限计算属性
const isSuperAdmin = computed(() => userStore.isAdmin())

// 生命周期
onMounted(() => {
  initPageData()
})

// 初始化页面数据
const initPageData = async () => {
  try {
    loading.value = true
    
    // 1. 首先判断是否为超级管理员
    if (isSuperAdmin.value) {
      // 超级管理员可以查看所有物业公司
      hasPropertyCompany.value = true
      await getPropertyCompanyList()
      return
    }
    
    // 2. 如果不是超级管理员，检查是否有关联物业公司
    // 优先使用store中的公司信息，如果store中没有则调用API检查
    if (userStore.hasCompany !== null) {
      hasPropertyCompany.value = userStore.hasCompany
      if (hasPropertyCompany.value) {
        // 有关联物业公司，获取列表数据（只显示关联的公司）
        await getPropertyCompanyList()
      }
    } else {
      // store中没有公司信息，调用API检查
      try {
        const hasCompanyRes = await propertyInfoApi.hasPropertyCompany()
        hasPropertyCompany.value = hasCompanyRes.data || false
        
        // 更新store中的公司信息
        if (hasPropertyCompany.value) {
          await userStore.checkAndUpdateCompanyInfo()
          // 有关联物业公司，获取列表数据（只显示关联的公司）
          await getPropertyCompanyList()
        } else {
          // 没有关联物业公司，清除store中的公司信息
          userStore.clearCompanyInfo()
        }
      } catch (apiError) {
        console.error('检查物业公司关联失败:', apiError)
        // 如果API调用失败，可能是权限问题，设置为无关联状态
        hasPropertyCompany.value = false
        userStore.clearCompanyInfo()
      }
    }
  } catch (error) {
    console.error('初始化页面数据失败:', error)
    showError('页面数据加载失败')
  } finally {
    loading.value = false
  }
}

// 获取物业公司列表
const getPropertyCompanyList = async () => {
  try {
    loading.value = true
    
    // 根据用户权限添加数据权限过滤参数
    const params = { ...queryParams }
    
    // 如果不是超级管理员，添加数据权限过滤
    if (!isSuperAdmin.value) {
      // 非超级管理员只能查看自己关联的物业公司
      // 这里通过API参数传递权限范围，后端进行过滤
    }
    
    // 使用新的API调用方式，参数会自动过滤空值
    const response = await propertyCompanyApi.getPropertyCompanyList(params)
    if (response.code === 200) {
      let data = response.data.records || []
      total.value = response.data.total || 0
      
      // 移除前端的数据权限过滤，因为后端已经处理了数据权限
      // 后端返回的数据已经是经过权限过滤的，无需在前端再次过滤
      propertyCompanyList.value = data
    } else {
      showError(response.message || '获取物业公司列表失败')
    }
  } catch (error: any) {
    console.error('获取物业公司列表失败:', error)
    
    // 根据错误类型进行不同处理
    if (error.message && error.message.includes('权限不足')) {
      // 如果是超级管理员，不应该出现权限不足错误
      if (isSuperAdmin.value) {
        console.error('超级管理员出现权限不足错误，可能是后端权限配置问题')
        showError('系统权限配置异常，请联系管理员')
      } else {
        // 非超级管理员权限不足，说明没有关联物业公司
        hasPropertyCompany.value = false
        userStore.clearCompanyInfo()
        // 不显示错误提示，因为这是正常的权限控制
      }
    } else {
      showError('获取物业公司列表失败')
    }
  } finally {
    loading.value = false
  }
}

// 处理联系管理员
const handleContactAdmin = () => {
  showInfo('请联系系统管理员为您关联物业公司')
}

// 处理重新检查
const handleRefresh = async () => {
  await initPageData()
}

// 查询
const handleQuery = () => {
  queryParams.current = 1
  getPropertyCompanyList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.current = 1
  getPropertyCompanyList()
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增
const handleAdd = () => {
  formData.value = {}
  formVisible.value = true
}



// 查看
const handleView = (row: any) => {
  // 跳转到详情页面，显示用户列表
  router.push(`/property/company/detail/${row.id}`)
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除物业公司"${row.companyName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await propertyCompanyApi.deletePropertyCompany(row.id)
    if (response.code === 200) {
      showSuccess('删除成功')
      getPropertyCompanyList()
    } else {
      showError(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除物业公司失败:', error)
      showError('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    showWarning('请选择要删除的物业公司')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedIds.value.length}个物业公司吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await propertyCompanyApi.batchDeletePropertyCompany(selectedIds.value)
    if (response.code === 200) {
      showSuccess('批量删除成功')
      getPropertyCompanyList()
    } else {
      showError(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除物业公司失败:', error)
      showError('批量删除失败')
    }
  }
}

// 审核
const handleAudit = (row: any) => {
  auditCompanyId.value = row.id
  auditVisible.value = true
}

// 新增用户
const handleAddUser = (row: any) => {
  // 跳转到新增用户页面
  router.push(`/property/company/add-user/${row.id}`)
}

// 导出
const handleExport = () => {
  showInfo('导出功能待实现')
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  queryParams.size = size
  queryParams.current = 1
  getPropertyCompanyList()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  queryParams.current = current
  getPropertyCompanyList()
}

// 表单成功回调
const handleFormSuccess = () => {
  formVisible.value = false
  getPropertyCompanyList()
}

// 表单取消回调
const handleFormCancel = () => {
  formVisible.value = false
}

// 审核成功回调
const handleAuditSuccess = () => {
  auditVisible.value = false
  getPropertyCompanyList()
}

// 审核取消回调
const handleAuditCancel = () => {
  auditVisible.value = false
}

// 获取审核状态类型
const getAuditStatusType = (status: number) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'success'
    case 2: return 'danger'
    default: return 'info'
  }
}

// 获取审核状态文本
const getAuditStatusText = (status: number) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '已通过'
    case 2: return '已拒绝'
    default: return '未知'
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString()
}
</script>

<style scoped>
.property-company-list {
  padding: 20px;
}



.search-card {
  margin-bottom: 16px;
}

.operation-card {
  margin-bottom: 16px;
}

.operation-buttons {
  display: flex;
  gap: 12px;
}

.operation-buttons .el-button {
  padding: 4px 8px;
  font-size: 12px;
  min-height: auto;
  line-height: 1.2;
}

.operation-buttons .el-button + .el-button {
  margin-left: 0;
}

.table-card {
  margin-bottom: 16px;
}

.company-option {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.company-name {
  font-weight: 500;
  color: #303133;
}

.company-code {
  font-size: 12px;
  color: #909399;
}
</style> 